//
//  ViewController.m
//  JavaScript
//
//  Created by Rookie_YX on 16/7/18..
//  Copyright © 2016年 Rookie_YX. All rights reserved.
//

#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>

@protocol JSObjcDelegate <JSExport>
- (void)call;
- (void)getCall:(NSString *)callString;
@end

@interface ViewController ()<UIWebViewDelegate,JSObjcDelegate>
@property (nonatomic, strong) JSContext *jsContext; // js上下文
@property (strong, nonatomic)  UIWebView *webView;
@property (nonatomic, copy) NSString *str;
@end

@implementation ViewController

#pragma mark - life cycle
- (void)viewDidLoad {
  
    [super viewDidLoad];
  // 定义一个值传给Web端
  self.str = @"OC代码中传过来的值";
  
  // 加载 webView
  self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
  self.webView.delegate = self;
  
  // 请求webview
  NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
  NSURL* url = [NSURL fileURLWithPath:path];
  NSURLRequest* request = [NSURLRequest requestWithURL:url] ;
  [self.webView loadRequest:request];

  [self.view addSubview:self.webView];
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.jsContext[@"YXRookie"] = self;
    self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
        context.exception = exceptionValue;
        NSLog(@"异常信息：%@", exceptionValue);
    };
}

#pragma mark - JSObjcDelegate
- (void)call{
    NSLog(@"call");
    // 之后在回调js的方法Callback把内容传出去
    JSValue *Callback = self.jsContext[@"Callback"];
    //传值给web端
    [Callback callWithArguments:@[self.str]];
}

- (void)getCall:(NSString *)callString{
    NSLog(@"Get:%@", callString);
    // 成功回调js的方法Callback
    JSValue *Callback = self.jsContext[@"alerCallback"];
    [Callback callWithArguments:nil];
}

@end
